package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasCoUserModel;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.SysUserHelp;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author: wufeng
 * @date: 2018/11/30 18:58
 * @desrcption: 获取用户
 */
@Component
public class UserHelp {

    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private PaasCoUserModel paasCoUserModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private SysUserHelp sysUserHelp;

    /**
     * 获取用户和部门的容器
     * @param userAndDepartmentGetDTO
     * @return
     * @throws XbbException
     */
    public UserAndDepartmentGetVO getUserDepartmentMap(UserAndDepartmentGetDTO userAndDepartmentGetDTO) throws XbbException{
        return commonHelp.getUserDepartmentMap(userAndDepartmentGetDTO, BasicConstant.ZERO);
    }
    
    /**
     * 获取用户和部门的容器
     * @param userAndDepartmentGetDTO
     * @param LeaveMarks 是否需要离职标志
     * @return
     * @throws XbbException
     */
    public UserAndDepartmentGetVO getUserDepartmentMap(UserAndDepartmentGetDTO userAndDepartmentGetDTO,Integer LeaveMarks) throws XbbException{
        return commonHelp.getUserDepartmentMap(userAndDepartmentGetDTO, LeaveMarks);
    }
    
    /**
     * 获取所有用户的容器
     * @param userAndDepartmentGetDTO
     * @return
     * @throws XbbException
     */
    public Map<String, UserEntity> getUserMap(UserAndDepartmentGetDTO userAndDepartmentGetDTO) throws XbbException {
        return commonHelp.getUserMap(userAndDepartmentGetDTO,BasicConstant.ONE);
    }

    /**
     * 获取所有用户的容器
     * @param userAndDepartmentGetDTO
     * @return
     * @throws XbbException
     */
    public Map<String, DepartmentEntity> getDepartmentMap(UserAndDepartmentGetDTO userAndDepartmentGetDTO) throws XbbException {
        return commonHelp.getDepartmentMap(userAndDepartmentGetDTO);
    }








    public void setOwnerAndCoUser(JSONObject data, PaasFormDataEntityExt paasFormDataEntityExt, Integer saasMark, Integer businessType, Map<String, UserEntity> userMap) throws XbbException {
        String corpid = paasFormDataEntityExt.getCorpid();
        String ownerId = paasFormDataEntityExt.getOwnerId();
        Long dataId = paasFormDataEntityExt.getId();
        // 负责人
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        List<String> ownerIdList = new ArrayList<>();
        if (userTeamEnum == UserTeamEnum.UNKNOW) {
            ownerIdList.add(ownerId);
        } else {
            Map<Long, List<UserTeamEntity>> userTeamMap = userTeamService.getMainUserTeamListMap(Collections.singletonList(dataId), paasFormDataEntityExt.getCorpid(), businessType, false);
            if (userTeamMap.containsKey(dataId)) {
                List<UserTeamEntity> userTeamEntities = userTeamMap.get(dataId);
                userTeamEntities.forEach(item->{
                    ownerIdList.add(item.getUserId());
                });
            }
        }
        Map<String, Object> delUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userMap.values().forEach(userEntity -> {
            if (!Objects.equals(userEntity.getDel(), DelEnum.NORMAL.getDel())) {
                delUserMap.put(userEntity.getUserId(), userEntity);
            }
        });
        ownerIdList.removeIf(delUserMap::containsKey);
        data.put(FieldTypeEnum.OWNERID.getAlias(), ownerIdList);
        List<String> coUserIdList = new ArrayList<>();
        Map<Long, List<UserTeamEntity>> userTeamMap = userTeamService.getCoUserMap(Collections.singletonList(dataId), paasFormDataEntityExt.getCorpid(), businessType);
        if (userTeamMap.containsKey(dataId)) {
            List<UserTeamEntity> userTeamEntities = userTeamMap.get(dataId);
            userTeamEntities.forEach(item->{
                coUserIdList.add(item.getUserId());
            });
        }
        coUserIdList.removeIf(delUserMap::containsKey);
        data.put(FieldTypeEnum.COUSERID.getAlias(), coUserIdList);

    }

    public Map<String, UserEntity> getUserMapByList(FieldAttrEntity fieldAttrEntity, List<PaasFormDataEntityExt> dataList, String corpid, boolean negDel) {
        Integer fieldType = fieldAttrEntity.getFieldType();
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(dataList) && ExplainUtil.isUser(fieldType)) {
            String attr = fieldAttrEntity.getAttr();
            Set<String> userIdSet = new HashSet<>();
            dataList.stream().map(PaasFormDataEntity::getData).filter(jsonObject -> !Objects.isNull(jsonObject)).forEach(jsonObject -> {
                if (Objects.equals(FieldTypeEnum.USER.getType(), fieldType)) {
                    String userId = jsonObject.getString(attr);
                    if (StringUtil.isNotEmpty(userId)) {
                        userIdSet.add(userId);
                    }
                } else if (Objects.equals(FieldTypeEnum.USER_GROUP.getType(), fieldType)) {
                    JSONArray jsonArray = jsonObject.getJSONArray(attr);
                    if (Objects.nonNull(jsonArray)) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String userId = jsonArray.getString(i);
                            if (StringUtil.isNotEmpty(userId)) {
                                userIdSet.add(userId);
                            }
                        }
                    }
                }
            });
            if (CollectionsUtil.isNotEmpty(userIdSet)) {
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(StringConstant.CORPID, corpid);
                param.put("userIdIn", userIdSet);
                if (negDel) {
                    // 排除已删除或已离职的用户
                    param.put("negDel", 1);
                }
                List<UserEntity> userList = userModel.findEntitys(param);
                if (CollectionsUtil.isNotEmpty(userList)) {
                    userList.forEach(item->{
                        userMap.put(item.getUserId(), item);
                    });
                }
            }
        }
        return userMap;
    }

    public Map<String, DepartmentEntity> getDepartmentMapByList(FieldAttrEntity fieldAttrEntity, List<PaasFormDataEntityExt> dataList, String corpid, boolean negDel) {
        Integer fieldType = fieldAttrEntity.getFieldType();
        Map<String, DepartmentEntity> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(dataList) && ExplainUtil.isDept(fieldType)) {
            String attr = fieldAttrEntity.getAttr();
            Set<Long> departmentIdSet = new HashSet<>();
            dataList.stream().map(PaasFormDataEntity::getData).filter(jsonObject -> !Objects.isNull(jsonObject)).forEach(jsonObject -> {
                if (Objects.equals(FieldTypeEnum.DEPT.getType(), fieldType)) {
                    Long departmentId = jsonObject.getLong(attr);
                    if (Objects.nonNull(departmentId)) {
                        departmentIdSet.add(departmentId);
                    }
                } else if (Objects.equals(FieldTypeEnum.DEPT_GROUP.getType(), fieldType)) {
                    JSONArray jsonArray = jsonObject.getJSONArray(attr);
                    if (Objects.nonNull(jsonArray)) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Long departmentId = jsonArray.getLong(i);
                            if (Objects.nonNull(departmentId)) {
                                departmentIdSet.add(departmentId);
                            }
                        }
                    }
                }

            });
            if (CollectionsUtil.isNotEmpty(departmentIdSet)) {
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(StringConstant.CORPID, corpid);
                param.put("departmentIdIn", departmentIdSet);
                if (negDel) {
                    // 获取未删除的部门
                    param.put("del", 0);
                }
                List<DepartmentEntity> userList = departmentModel.findEntitys(param);
                if (CollectionsUtil.isNotEmpty(userList)) {
                    userList.forEach(item->{
                        departmentMap.put(item.getId().toString(), item);
                    });
                }
            }
        }
        return departmentMap;
    }

    /**
     * @author 吴峰
     * @date 2021-03-17 09:44
     * @param
     * @return com.xbongbong.paas.toolbox.wrap.UserVO
     * @throws XbbException 业务异常
    */
    public UserVO getUserName(String corpid, String userId, String loginUserName, Integer flowStatus, String creatorId) {
        return sysUserHelp.getUserName(corpid, userId, loginUserName, flowStatus, creatorId);
    }
}
